package com.example.week11_service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.TextView;

import java.util.List;

public class RandomNumActivity extends AppCompatActivity {
    RandomNumService binderService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_random_num);
        findViewById(R.id.randomNumBtn).setOnClickListener(new View.OnClickListener() { @Override
        public void onClick(View view) {
            List number = binderService.getRandomNumber();
            String str = "";
            for (int i = 0; i < number.size(); i++) {
//将获取的号码转为 String 类型
                str += (number.get(i).toString() + "	");
            }
            TextView randomNumTxt = findViewById(R.id.randomNumTxt);

            randomNumTxt.setText(str);
        }
        });
    }
    @Override
    protected void onStart() { super.onStart();
//创建启动 Service 的 Intent
        Intent intent = new Intent(this, RandomNumService.class);
//绑定指定 Service
        bindService(intent, conn, BIND_AUTO_CREATE);
    }@Override
    protected void onStop() { super.onStop();
        unbindService(conn);	//解除绑定 Service
    }private ServiceConnection conn = new ServiceConnection() { @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
//获取后台 Service 信息
        binderService = ((RandomNumService.MyBinder) service).getService();
    }@Override
    public void onServiceDisconnected(ComponentName name) {
    }
    };
}


